<?php

class Models_ToolManga
{
    private static $_instance = null;
    
	private $_config;
 
	/**
	 * 
	 * @param array $options
	 */
    public function __construct()
    {
        $this->_config = new Zend_Config_Ini(APPLICATION_PATH . 'etc/manga.ini', APP_ENV);
    }
    
    /**
     * @param array $options
     * @return Models_ToolManga
     */
    public static function factory()
    {
        if (!self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    
    function getContentHtml($url) {
        $curl = curl_init($url);
        try {
            //curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
            curl_setopt($curl, CURLOPT_COOKIE, '__gads=ID=ca0887f19076f466:T=1357205096:S=ALNI_MZnmQtlKFcTgU0xT_nT__OJbMPVew; PHPSESSID=12oah5vvnkag4m2af0tajsomu5; __atuvc=1%7C2; pop1=popup1%20Popunder; pop2=pop2%20Popunder; pop3=pop3%20Popunder; location.href; thanksmanga68=1; __utma=46011704.819477726.1357205097.1358840405.1358846937.39; __utmb=46011704.1.10.1358846937; __utmc=46011704; __utmz=46011704.1357205097.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)');
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 10);
            $result = curl_exec($curl);
//                         prAli($result);
        } catch (Exception $exc) {
            prAli($exc->getMessage());
        }
        curl_close($curl);
    
        return $result;
    }
    
    function getTagImage($content)
    {
        $res = array();
//         file_put_contents('/home/gamezing/backend/public_html/../../frontend/public_html/test.html', $content);
        //         prAli($content);
        preg_match_all('/<img[^>]*>/', $content, $res);
//         prAli($res);
        return $res;
    }
    
    /**
     * Get src of tag <img>
     * @param string $url
     * @param bool $link true if $url is a link, false if file
     * @return multitype:string array link of image
     */
    function getLinkImage($url, $link = true)
    {
        if ($link) {
            $sitesHtml = $this->getContentHtml($url);
            //             $sitesHtml = file_get_contents($url);
        } else {
            $sitesHtml = file_get_contents($url);
        }
        //Get all meta tags and loop through them.
        $res = array();
        $tags = $this->getTagImage($sitesHtml);
        //         prAli($tags);
        $regexLink = $this->_config->filter_url;
        foreach($tags[0] as $tag) {
            $ele = new DOMDocument();
            @$ele->loadHTML($tag);
            $img = $ele->getElementsByTagName('img')->item(0);
            $prop = $img->getAttribute('src');
            if (!preg_match($regexLink, $prop)) {
                $prop = $img->getAttribute('tppabs');
            }
            if ($prop) {
                $res[] = $prop;
            }
        }
//         prAli($res);
        return $res;
    }
    
    /**
     * Get image from url to server
     * @param string $url
     * @param string $repository
     * @return string name of image on server
     */
    function getImageFromUrl($url, $repository, $suffix = '', $newName = '')
    {
        try {
            if (!$suffix) {
                $suffix = time();
            }
            $url = str_replace(' ', '%20', $url);
            $filename = basename($url);
            $fileName = str_replace(' ', '', $filename);
            $extension = pathinfo($fileName, PATHINFO_EXTENSION);
            $ext = 'jpg';
            preg_match('/jpg|jpeg|gif|png|bmp/', $extension, $ext);
            $e = $ext[0];
            if (!$e) {
                $e = 'jpg';
            }
            if ($newName) {
                $name = $newName;
            } else {
                $name = 'image_' . $suffix . '.' . $e;
            }
//             prAli($url);
            $ch = curl_init($url);
            $fp = fopen($repository . '/' . $name, 'wb');
            curl_setopt($ch, CURLOPT_FILE, $fp);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            $result = curl_exec($ch);
        } catch (Exception $exc) {
//             prAli($exc->getMessage());
            curl_close($ch);
            fclose($fp);
            throw new Exception('The given destination is not writeable');
            return;
        }
        curl_close($ch);
        fclose($fp);
//         prAli($repository . '/' . $name);
        if (filesize($repository . '/' . $name) > 0) {
            return $name;
        }
    
        return '';
    }
    
    /**
     * Save image from url to static
     * @param array $arrUrl array content url
     * @param string $repository path save example: 0001/Ten cua truyen
     * @return multitype:string
     */
    function saveImageToStatic($arrUrl, $repository, $suffix = null)
    {
        $res = array();
        if (!$suffix) {
            $suffix = time();
        }
        $count = 0;
        $path = $this->_config->destinationUpload . '/' . $repository;
        if (!is_writable($path)) {
            throw new Exception('The given destination is not writeable');
            return;
        }
        foreach($arrUrl as $url) {
            //             prAli($this->_config->destinationUpload . '/' . $repository);
            $name = $this->getImageFromUrl($url, $path, $suffix);
//             if ($name) {
                $suffix++;
//                 prAli($name);
                //$this->uploadFileToStatic($path . '/' . $name, $this->_config->ftp->manga_repository . '/' . $repository);
                $res[$count] = array('link' => $url,
					'name' => $name,
				);
                $count++;
//             }
        }
        return $res;
    }
    
    /*
     * upload image to static
    */
    public function uploadFileToStatic($file, $ftpPath = null, $fileName = null){
        try {
            $fp = fopen($file, 'r');
            if (!$fileName) {
                $fileName = basename($file);
            }
            $conn_id = ftp_connect($this->_config->ftp->host);
            $login_result = ftp_login($conn_id, $this->_config->ftp->username, $this->_config->ftp->pwd);
            if (!$ftpPath) {
                $ftpPath = $this->_config->ftp->path;
            }
            if (!ftp_chdir($conn_id, $ftpPath)) {
                ftp_mkdir($conn_id, $ftpPath);
            }
             
            ftp_close($conn_id);
            $conn_id = ftp_connect($this->_config->ftp->host);
            $login_result = ftp_login($conn_id, $this->_config->ftp->username, $this->_config->ftp->pwd);
    
            //             prAli($ftpPath);
            if (ftp_fput($conn_id, $ftpPath .'/'. $fileName, $fp, FTP_BINARY)) {
                return true;
            } else {
                throw new Exception("upload file error dsfad");
            }
            ftp_close($conn_id);
            fclose($fp);
        }catch(Exception $e){
            prAli($e);
        }
    }
    
    public function moveChapterOrder($mangaId, $from, $to, $moveTop = true)
    {
        $db = Globals::getDbConnection('maindb', false);
        //get all id < order $from
        $idsDown = $db->fetchAll('SELECT sub_id, `order` FROM sub_manga WHERE id = ' . $mangaId . ' AND `order` < ' . $from . ' ORDER BY `order` ASC');
        $idsUp = $db->fetchAll('SELECT sub_id, `order` FROM sub_manga WHERE id = ' . $mangaId . ' AND `order` >= ' . $from . ' AND `order` <= ' . $to . ' ORDER BY `order` ASC');
//         prAli($idsDown, 0);

        //get delta down, delta up
        $length = count($idsDown);
        $deltaDown = $to - $idsDown[$length - 1]['order'];
        $deltaUp = $from - $idsDown[0]['order'];
        
        foreach($idsDown as $id) {
            $order = array('order' => $id['order'] + $deltaDown);
            $db->update('sub_manga', $order, 'id=' . $mangaId . ' AND sub_id=' . $id['sub_id']);
        }
        
        foreach($idsUp as $id) {
            $order = array('order' => $id['order'] - $deltaUp);
            $db->update('sub_manga', $order, 'id=' . $mangaId . ' AND sub_id=' . $id['sub_id']);
        }
    }
}